package aar.test.tessocr;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.w3c.dom.Text;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import aar.test.tessocr.base.AppManager;
import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CabinetModel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.tessOcrUtil.CameraView;
import aar.test.tessocr.tessOcrUtil.RecycledImageView;
import aar.test.tessocr.tessOcrUtil.TesseractUtil;
import aar.test.tessocr.tessOcrUtil.TextImageProcessor;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.LogUtils;
import aar.test.tessocr.utils.TipHelper;
import aar.test.tessocr.utils.UnzipAssets;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.utils.statuesBar;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static aar.test.tessocr.LoginActivity.JSON;

public class MainActivity extends BaseActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    private DisplayMetrics dm;

    private Context mContext;

    private CameraView mCameraView;

    private RecycledImageView mImageView,main_image2,main_image3,main_image4,main_image5,main_image6,main_image7;

    private EditText show_text;

    private TextView ok_text;

    private TextView cal_text;

    private String text;

    //两秒退出的标志
    private boolean isExit = false;

    private TextImageProcessor processor;

    Bitmap  map;

    List<MatOfPoint> mats;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_main);
        if (null != getSupportActionBar()) {
            getSupportActionBar().hide();
        }
        statuesBar.setStatusBarFullTransparent(this);

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        iniLoadOpenCV();

        if (Build.VERSION.SDK_INT >= 23) {
            requestP();

        } else {

            unZipAssset();
        }
        processor = new TextImageProcessor();

        // Example of a call to a native method
//        TextView tv = findViewById(R.id.sample_text);
//        tv.setText(stringFromJNI());
        mCameraView =  findViewById(R.id.main_camera);
        mImageView =  findViewById(R.id.main_image);
        main_image2 =  findViewById(R.id.main_image2);
        main_image3 =  findViewById(R.id.main_image3);
        main_image4 =  findViewById(R.id.main_image4);
        main_image5 =  findViewById(R.id.main_image5);
        main_image6 =  findViewById(R.id.main_image6);
        main_image7 =  findViewById(R.id.main_image7);

        show_text=findViewById(R.id.show_text);
        mCameraView.setTag(mImageView);
        mCameraView.setShowImage(main_image2);
        mCameraView.setShowImage3(main_image3);
        mCameraView.setShowImage4(main_image4);
        mCameraView.setShowImage5(main_image5);
        mCameraView.setShowImage6(main_image6);
        mCameraView.setShowImage7(main_image7);

        mCameraView.setShowTextListener(new CameraView.showTextListener() {
            @Override
            public void getRecBitmap(final Bitmap bap) {

//                if(null!=bap){
//                    mats=new ArrayList<>();
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            main_image2.setImageBitmap(bap);
//                        }
//                    });
//                    Mat  bapMat=new Mat();
//                    Utils.bitmapToMat(bap,bapMat);
//                    mats= processor.findCard(bapMat);
//                    bapMat.release();
//
//                    if(null!=bapMat2){
//                        Log.e("MainActivity","findCard---6666666666666666666666666==bapMat2.cols()=="+bapMat2.cols()+"-------bapMat2.rows()=="+bapMat2.rows());
//
//                        map=Bitmap.createBitmap(numImage.cols(),numImage.rows(), Bitmap.Config.ARGB_8888);
//                        Utils.matToBitmap(numImage,map);
//
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//
//                                if(null!=map){
//                                    Log.e("MainActivity","findCard---7777777777777777777777777--map=="+map.getHeight()+"------map.getWidth()=="+map.getWidth());
//                                    mImageView.setImageBitmap(map);
//                                }
//
////                                map=null;
//
//                            }
//                        });
//
////                        bapMat2.release();
//                    }
//
//
//
//                }

            }

            @Override
            public void showText( String tt) {

                           text =tt;
                TipHelper.Vibrate(MainActivity.this,1000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if(!TextUtils.isEmpty(text)){
                            show_text.setText(text);
                            show_text.setSelection(text.length());
                        }

                    }
                });

            }
        });
        cal_text=findViewById(R.id.cal_text);
        cal_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(null!=mCameraView){
                    mCameraView.isScanning=false;
                }

                if(null!=show_text){
                    show_text.setText("");
                }

            }
        });

        ok_text=findViewById(R.id.ok_text);
        ok_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //do something

//                choiceCab();
//                openExpressGrid();


                String scanp= show_text.getText().toString().replaceAll(" ","");
                if(!TextUtils.isEmpty(scanp)){
                    BaseApplication.getIntance().setScanPhoneNub( scanp);

                    startActivityForResult(new Intent(MainActivity.this,ChioceCabActivity.class),100);
                }else{

                    Toast.makeText(mContext,getResources().getString(R.string.error_invalid_phonenum),Toast.LENGTH_LONG).show();
                }




            }
        });




    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==100){

            if(null!=mCameraView){
                mCameraView.isScanning=false;
            }
            if(null!=show_text){
                show_text.setText("");
            }
        }




    }

    private void companyInf(){

        Map<String ,Object> map=new HashMap<>();
        map.put("companyNum",2);

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse<loginModel>>post(Urls.URL_COMPANYINFO)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<loginModel>>(MainActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<loginModel>> response) {


                        Log.e("MainActivity","onSuccess-----logout---------------"+response.body().data);



                    }

                    @Override
                    public void onError(Response<LzyResponse<loginModel>> response) {
                        Log.e("MainActivity","onError---------------------");
                    }
                });



    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //Activity销毁时，取消网络请求
        OkGo.getInstance().cancelTag(this);

        loginOut();


    }

    private void loginOut(){

        if(null==BaseApplication.getIntance().getLoginBean().getId()){
            return;
        }

        Map<String ,Object> map=new HashMap<>();
        map.put("userid",BaseApplication.getIntance().getLoginBean().getId());

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse<loginModel>>post(Urls.URL_LOGOUT)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<loginModel>>(MainActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<loginModel>> response) {
                        BaseApplication.getIntance().setLogin(false);
                        BaseApplication.getIntance().setLoginBean(null);

                        Log.e("MainActivity","onSuccess-----logout---------------");



                    }

                    @Override
                    public void onError(Response<LzyResponse<loginModel>> response) {
                        Log.e("MainActivity","onError---------------------");
                    }
                });



    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    private void requestP() {

        AndPermission.with(this)
                .requestCode(ConstantPara.REQUEST_CODE_PERMISSION_SD)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).
                                show();
                    }
                })
                .start();
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(MainActivity.this, "111111111111", Toast.LENGTH_SHORT).show();
                    unZipAssset();
                    break;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(ShowMobleSDMediaActivity.this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();
                    break;
                }

            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, deniedPermissions)) {

                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(MainActivity.this, ConstantPara.REQUEST_CODE_SETTING, dm).show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            }
        }
    };


    private void unZipAssset() {

        prepareSdPath();

        prepareSdPath2();

        try {

            File file = new File(TesseractUtil.TESSBASE_PATH_DOWN);

            File file2 = new File(TesseractUtil.TESSBASE_PATH_DOWN + "/normal.traineddata");

            if (!file.exists() || (file.exists() && !file2.exists())) {
                new Thread() {
                    public void run() {
                        //在新线程中以同名覆盖方式解压
                        UnzipAssets.unZip(MainActivity.this, ConstantPara.UN_ZIP_ASSET_NAME, TesseractUtil.TESSBASE_PATH, true);
                    }
                }.start();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath() {

        try {

            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRootThumbnail = new File(TesseractUtil.TESSBASE_PATH);
                if (!sPathRootThumbnail.exists()) {
                    sPathRootThumbnail.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            click2Back();
        }
        return false;
    }


    //按两次退出程序
    private void click2Back() {
        Timer tExit;
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, getResources().getString(R.string.click_the_exit_program_again), Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {

                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            //退出程序
            loginOut();
            AppManager.getAppManager().finishAllActivity();
            finish();
            System.exit(0);
        }
    }




    private void iniLoadOpenCV() {
        boolean success = OpenCVLoader.initDebug();
        if(success) {
            Log.e("MainActivity", "OpenCV Library loaded...");
        } else {
            Toast.makeText(this.getApplicationContext(), "could not load opencv lib...", Toast.LENGTH_LONG).show();
        }
    }



    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath2() {

        String RootFilePath = Environment.getExternalStorageDirectory() + "/DCIM/";

        String sSubDir = "normal";
//        String RootFilePath=  Environment.getExternalStorageDirectory() + "/Download/";

        try {


            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRoot = new File(RootFilePath);
                if (!sPathRoot.exists()) {
                    sPathRoot.mkdirs();
                }
                File sPathVid = new File(RootFilePath + sSubDir);
                LogUtils.e("MainActivity", "sPathVid.exists()==" + sPathVid.exists());
                if (!sPathVid.exists()) {
                    sPathVid.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }











}
